from django.db import transaction
from rest_framework.views import APIView
from django.db.models import F
from rest_framework.decorators import action
from rest_framework import generics
from apps.project_case.models import House
from apps.system.models import Upload
from apps.member.models import MemberRecord
from utils import response_error, response_ok
from utils.custom_modelviewset import CustomModelViewSet
from utils.exceptions import CustomError
from utils.permission import IsMemberUser
from .models import Circle, CircleComment
from .serializers import CircleAppSerializer, CircleHouseSerializer, CircleCommentSerializer
from .filters import CircleCommentFilter


class CircleDetailView(generics.RetrieveAPIView):
    queryset = Circle.objects.filter()
    serializer_class = CircleAppSerializer

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        Circle.objects.filter(id=instance.id).update(brown_count=F('brown_count') + 1)
        return super(CircleDetailView, self).retrieve(request, *args, **kwargs)


class CircleListView(generics.ListAPIView):
    queryset = Circle.objects.filter()
    serializer_class = CircleAppSerializer


class CircleCommentListView(generics.ListAPIView):
    queryset = CircleComment.objects.filter()
    serializer_class = CircleCommentSerializer

    def filter_queryset(self, queryset):
        f = CircleCommentFilter(self.request.GET, queryset=self.queryset)
        return f.qs


class HouseListView(generics.ListAPIView, generics.RetrieveAPIView):
    permission_classes = [IsMemberUser, ]
    queryset = House.objects.filter(is_complete=False, delete=False)
    serializer_class = CircleHouseSerializer

    def paginate_queryset(self, queryset):
        return None


class CircleCommentViewSet(CustomModelViewSet):
    permission_classes = [IsMemberUser, ]
    queryset = CircleComment.objects.filter()
    serializer_class = CircleCommentSerializer

    @action(methods=['get'], detail=True)
    def like(self, request, pk):
        try:
            circle_comment = CircleComment.get_instance_by_id(pk)
            with transaction.atomic():
                like, messgae = MemberRecord.like_operate(circle_comment, self.request.user.member)
                return response_ok({
                    'like': like,
                    'messgae': messgae
                })
        except Exception as e:
            return response_error(str(e))


class CircleViewSet(CustomModelViewSet):
    permission_classes = [IsMemberUser, ]
    queryset = Circle.objects.filter()
    serializer_class = CircleAppSerializer

    def create(self, request, *args, **kwargs):
        try:
            content = request.data.get('content', None)
            house_id = request.data.get('house', None)
            images = request.data.get('images', None)
            if not content or not house_id or not images:
                raise CustomError('参数为空')
            house = House.get_instance_by_id(house_id)
            # if content:
            #     # 小程序敏感词校验
            #     wechat_applet = WeChatApplet()
            #     wechat_applet.wx_check_content(content)
            with transaction.atomic():
                print(self.request.user.member)
                circle = Circle.objects.create(content=content, house=house, member=self.request.user.member)
                circle.images.add(*images)
        except Exception as e:
            return response_error(str(e))
        return response_ok()

    @action(methods=['get'], detail=True)
    def like(self, request, pk):
        try:
            circle = Circle.get_instance_by_id(pk)
            with transaction.atomic():
                like, messgae = MemberRecord.like_operate(circle, self.request.user.member)
                return response_ok({
                    'like': like,
                    'messgae': messgae
                })
        except Exception as e:
            return response_error(str(e))

    @action(methods=['post'], detail=True)
    def comment(self, request, pk):
        try:
            circle = Circle.get_instance_by_id(pk)
            content = request.data.get('content', None)
            if not content:
                raise CustomError('内容不能为空。')
            with transaction.atomic():
                CircleComment.objects.create(member=self.request.user.member, circle=circle, content=content)
        except Exception as e:
            return response_error(str(e))
        return response_ok()

    @action(methods=['post'], detail=False)
    def upload_image(self, request):
        file = request.FILES.get('file')
        if not file:
            return response_error(u'未找到上传的数据')
        try:
            with transaction.atomic():
                upload = Upload.objects.upload(file, 'circle')
                return response_ok({
                    'id': upload.id
                })
        except Exception as e:
            return response_error(str(e))
